package com.smartlink.service;

import java.util.List;

import org.json.JSONObject;

import com.smartlink.dao.SensorsDaoImpl;
import com.smartlink.pojo.Sensors;
import com.smartlink.util.HttpClientUtil;

public class SensorsService {
	private SensorsDaoImpl sensorsDao;
	private HttpClientUtil clientUtil;

	public void setClientUtil(HttpClientUtil clientUtil) {
		this.clientUtil = clientUtil;
	}

	public void setSensorsDao(SensorsDaoImpl sensorsDao) {
		this.sensorsDao = sensorsDao;
	}

	public boolean save(Sensors sensors, String device_id) {
		// 开关不需要网络上传
		if (sensors.getType() == 2) {
			sensors.setDsUuid("0000");
			sensorsDao.insert(sensors);
			return true;
		} else {

			String url = "http://api.heclouds.com/devices/" + device_id + "/datastreams";
			JSONObject sendData = new JSONObject();
			sendData.put("id", sensors.getSensorsName());
			sendData.put("unit", sensors.getUnit());
			sendData.put("unit_symbol", sensors.getUnitSymbol());
			JSONObject getData = clientUtil.doPost(url, sendData);
			if (getData != null) {
				int errno = getData.getInt("errno");
				if (0 == errno) {
					String ds_uuid = getData.getJSONObject("data").getString("ds_uuid");
					sensors.setDsUuid(ds_uuid);
					sensorsDao.insert(sensors);
					return true;
				}

				return false;
			}
		}
		return false;

	}

	public List<Sensors> getAll(int clsroomId) {
		return sensorsDao.getAll(clsroomId);
	}

	public List<Sensors> getEnvSensors(int clsroomId) {
		int type = 1;// 环境传感器的类型
		return sensorsDao.getSensorByType(clsroomId, type);
	}

	public List<Sensors> getSafeSensors(int clsroomId) {
		int type = 0;// 安全传感器的类型
		return sensorsDao.getSensorByType(clsroomId, type);
	}

}
